package com.qingmu.club.minaapi.custom.logic;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmu.club.minaapi.model.AccessToken;
import com.qingmu.club.minaapi.plus.entity.PushMessage;
import com.qingmu.club.minaapi.plus.service.PushMessageService;
import com.qingmu.club.minaapi.utils.CommonException;
import com.qingmu.club.minaapi.utils.HttpUtils;
import com.qingmu.club.minaapi.wechat.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class PushMessageLogic {

    private static String evaluateSendTemplateId="Fxonrqh8aTmN8B9O1EkkiR8jT2w0EJUKqE9pFrnUQis"; //会员对教练评价推送
    private static String evaluateSendJfExchangeTemplateId="e0jSq1tuQUgn890VVf_Eb6H81kUnFEN4-_SWDWzmKOg"; //积分兑换成功推送
    private static String evaluateSendGroupSuccessTemplateId="vrrkNsuUViA5ZcrzEhI40hUikh5Z29n8mB0dKdskuQk"; //拼团成功推送

    @Autowired
    PushMessageService pushMessageService;

    public PushMessage queryPushMessageList(String userId){
        QueryWrapper<PushMessage> qw = new QueryWrapper<>();
        qw.eq(PushMessage.USER_ID,userId);
        qw.eq(PushMessage.IS_USE,false);

        List<PushMessage> pushMessages =this.pushMessageService.list(qw);
        if(CollectionUtils.isEmpty(pushMessages)){
            return null;
        }
        //把7天前的删除
        for(PushMessage pushMessage : pushMessages){
            Calendar cal=Calendar.getInstance();
            cal.setTime(pushMessage.getCreateTime());
            cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 6);
            Date today = cal.getTime();
            if(today.before(new Date())){
                this.pushMessageService.removeById(pushMessage.getId());
            }
        }
        return pushMessages.get(0);
    }



    //发送会员对教练评价推送
    public String sendTemplate(String openid,String formId,String content,Integer evaluateStar,String evaluator) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String access_token = getAccessToken(WechatUtil.clubAppId,WechatUtil.clubAppSecret);
            String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;

            Map<String, Object> map = new HashMap<>();
            map.put("touser", openid);
            map.put("form_id", formId);
            map.put("page","/pages/CoachInfo/index");
            map.put("template_id",evaluateSendTemplateId);

            Map<String, Object> data = new HashMap<>();

            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value",content);
            data.put("keyword1",keyword1);

            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value",evaluateStar);
            data.put("keyword2",keyword2);

            Map<String, Object> keyword3 = new HashMap<>();
            keyword3.put("value",evaluator);
            data.put("keyword3",keyword3);

            map.put("data",data);
            String jsonStr = JSONObject.toJSONString(map);
            System.out.println("jsonStr:"+jsonStr);
            String ret = HttpUtils.requestPostBody(url, jsonStr, null);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //获取access_token
    public String getAccessToken(String appid, String appsecret) {
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        try {
            String json = HttpUtils.requestGet(url, null, null);
            AccessToken accessToken = JSON.parseObject(json,new TypeReference<AccessToken>(){});
            return accessToken.getAccess_token();
        } catch (CommonException e) {
            e.printStackTrace();
            return "";
        }
    }

    //积分兑换成功发送模板消息
    public String sendJfExchangeTemplate(String openid,String formId,String goodsName,Integer goodsPrices,Integer userJf,String shopName,Date applyTime,Date exchangeTime) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String access_token = getAccessToken(WechatUtil.memberAppId,WechatUtil.memberAppSecret);
            String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;

            Map<String, Object> map = new HashMap<>();
            map.put("touser", openid);
            map.put("form_id", formId);
            map.put("page","/pages/CoachInfo/index");
            map.put("template_id",evaluateSendJfExchangeTemplateId);

            Map<String, Object> data = new HashMap<>();

            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value",goodsName);
            data.put("keyword1",keyword1);

            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value",goodsPrices);
            data.put("keyword2",keyword2);

            Map<String, Object> keyword3 = new HashMap<>();
            keyword3.put("value",userJf);
            data.put("keyword3",keyword3);

            Map<String, Object> keyword4 = new HashMap<>();
            keyword4.put("value",shopName);
            data.put("keyword4",keyword4);

            Map<String, Object> keyword5 = new HashMap<>();
            keyword5.put("value",sdf.format(applyTime));
            data.put("keyword5",keyword5);

            Map<String, Object> keyword6 = new HashMap<>();
            keyword6.put("value",sdf.format(exchangeTime));
            data.put("keyword6",keyword6);

            map.put("data",data);
            String jsonStr = JSONObject.toJSONString(map);
            System.out.println("jsonStr:"+jsonStr);
            String ret = HttpUtils.requestPostBody(url, jsonStr, null);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    //魔力拼团成功发送模板消息
    public String sendGroupSuccessTemplate(String openid,String formId,String courseName,Integer groupNumber,String groupName,String mobile) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String access_token = getAccessToken(WechatUtil.memberAppId,WechatUtil.memberAppSecret);
            String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;

            Map<String, Object> map = new HashMap<>();
            map.put("touser", openid);
            map.put("form_id", formId);
            map.put("page","/pages/CoachInfo/index");
            map.put("template_id",evaluateSendGroupSuccessTemplateId);

            Map<String, Object> data = new HashMap<>();

            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value",courseName);
            data.put("keyword1",keyword1);

            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value",groupNumber);
            data.put("keyword2",keyword2);

            Map<String, Object> keyword3 = new HashMap<>();
            keyword3.put("value",groupName);
            data.put("keyword3",keyword3);

            Map<String, Object> keyword4 = new HashMap<>();
            keyword4.put("value",mobile);
            data.put("keyword4",keyword4);


            map.put("data",data);
            String jsonStr = JSONObject.toJSONString(map);
            System.out.println("jsonStr:"+jsonStr);
            String ret = HttpUtils.requestPostBody(url, jsonStr, null);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}